//
//  meiyongViewController.m
//  1243
//
//  Copyright © 2016年 1243. All rights reserved.
//

#import "meiyongViewController.h"

#import "OfferToSellViewController.h"//发布出售Controller
#import "OfferToBuyViewController.h"//发布购买Controller
#import "BuyCouponViewController.h"//购买企业券Controller
#import "HavingSalesViewController.h"//进行出售Controller
#import "HavingPurchasedViewController.h"//进行购买Controller
#import "NetWorkTools.h"
#import "QiyequanMineViewController.h"

#import "SellRecordModel.h"//出售记录Model
#import "BuyRecordModel.h"//购买记录Model
#import "ZheXianView.h"

#import "SalesTableViewHeaderView.h"//TableViewHeaderView
#import "SalesTableViewCell.h"//TableViewCell

@interface meiyongViewController ()<UITableViewDelegate, UITableViewDataSource,UIWebViewDelegate>

@property (nonatomic,strong) UITableView *havingToSellTableView;//进行出售TableView
@property (nonatomic,strong) UITableView *havingToBuyTableView;//进行购买TableView

@property(nonatomic,retain)UIWebView *webView;
@property (nonatomic,strong)BuyerInformationView *BuyerInformationView;

@end

@implementation meiyongViewController
{
    NSMutableArray *_sellRecordDataArray;  //出售记录
    NSMutableArray *_buyRecordDataArray;   // 购买记录
}


 static NSString * const offerCellID = @"offerCellID";


- (void)viewWillAppear:(BOOL)animated{
    
    if (_buyRecordDataArray.count > 0 || _sellRecordDataArray.count > 0) {
        [_buyRecordDataArray removeAllObjects];
        [_sellRecordDataArray removeAllObjects];
        
        //网络请求
        [self getSellRecord];
        [self getBuyRecord];
    }
    
    
    //刷新购买者信息自定义View
    [self createBuyerInformationView];
    [_buyerInformationView getUserData];
}
- (void)viewWillDisappear:(BOOL)animated{
    [_buyerInformationView removeFromSuperview];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化数据源
    [self createDataArray];
    
    //TableView页眉页脚
    [self createTableViewHeaderFooterView];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"企业券";
    
    self.automaticallyAdjustsScrollViewInsets = false;
    [self creatLine];
    [self createPriceAndQty];
    
    
    [self createBuyCouponView];
    
    [self getMarketPrice];
}


- (void)creatLine{
    UIView *a = [[UIView alloc] initWithFrame:CGRectMake(0, 64, WIDTH/5 *4, SCREEN_HEIGHT * 0.4 - 32)];
  //  [self.view addSubview:a];
    [a setBackgroundColor:[UIColor whiteColor]];
 
   
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 64, WIDTH/5 *4 - 20, SCREEN_HEIGHT * 0.4 - 70)];
    [self.view addSubview:self.webView];
    //代理人
    self.webView.delegate = self;
  
    NSString *string = @"http://114.55.30.134:8089/UserCenter/EnterpriseTicketmini?";
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    

}

- (void)createPriceAndQty{
    for (int i = 0; i < 3; i++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake( WIDTH / 5 * 4, 74 + i * ((SCREEN_HEIGHT * 0.4 - 80) / 3), WIDTH / 5 - 10, (SCREEN_HEIGHT * 0.4 - 94) / 3 + 1)];
        view.backgroundColor = [UIColor blueColor];
        [self.view addSubview:view];
        
        UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(1, 1, view.frame.size.width - 2, view.frame.size.height - 2)];
        view1.backgroundColor = [UIColor whiteColor];
        [view addSubview:view1];
        
        UILabel *string = [[UILabel alloc] initWithFrame:CGRectMake(0, view1.frame.size.height / 2 - 25, view1.frame.size.width, 20)];
        string.adjustsFontSizeToFitWidth = YES;
        string.textAlignment = NSTextAlignmentCenter;
        string.font = [UIFont systemFontOfSize:14];
        if (i == 0) {
            string.text = @"市场价";
        }else if (i == 1){
            string.text = @"日购买量";
        }else string.text = @"总购买量";
        [view1 addSubview:string];
        
        UILabel *num = [[UILabel alloc] initWithFrame:CGRectMake(0, view1.frame.size.height / 2, view1.frame.size.width, 20)];
        num.textAlignment = NSTextAlignmentCenter;
        num.font = [UIFont systemFontOfSize:14];
        num.textColor = [UIColor orangeColor];
        num.tag = i + 233;
        num.adjustsFontSizeToFitWidth = YES;
        [view1 addSubview:num];
    }
}

- (void)dataForLine{
    //  曲线图 数据
    
    NSDictionary *params2 = @{
                              //
                              @"GraphType":@"1"
                              };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params2 AndMenthodName:@"getGraph" completeBlock:^(id object) {
        NSString *str = object[@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:str];

        NSLog(@"arrarr%@",arr);
    }];
}

#pragma mark === TableView页眉页脚 ===
- (void)createTableViewHeaderFooterView{
    //页眉
    SalesTableViewHeaderView *sellHeaderView = [[SalesTableViewHeaderView alloc] initWithFrame:CGRectMake(10,SCREEN_HEIGHT * 0.4, (SCREEN_WIDTH - 30) / 2, 40)];
    
    [self.view addSubview:sellHeaderView];
    
    
    SalesTableViewHeaderView *buyHeaderView = [[SalesTableViewHeaderView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 + 5,SCREEN_HEIGHT * 0.4, (SCREEN_WIDTH - 30) / 2, 40)];
    
    [self.view addSubview:buyHeaderView];
    
    //页脚
    UIButton *sellBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sellBtn.frame = CGRectMake(10,SCREEN_HEIGHT * 0.74, (SCREEN_WIDTH - 30) / 2, SCREEN_HEIGHT * 0.06);
    sellBtn.backgroundColor = [UIColor orangeColor];
    [sellBtn setTitle:@"发布出售" forState:UIControlStateNormal];
    [sellBtn addTarget:self action:@selector(offerToSellClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sellBtn];
    
    UIButton *buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    buyBtn.frame = CGRectMake(SCREEN_WIDTH / 2 + 5,SCREEN_HEIGHT * 0.74, (SCREEN_WIDTH - 30) / 2, SCREEN_HEIGHT * 0.06);
    buyBtn.backgroundColor = [UIColor orangeColor];
    [buyBtn setTitle:@"发布购买" forState:UIControlStateNormal];
    [buyBtn addTarget:self action:@selector(offerToBuyClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buyBtn];
    
}

#pragma mark === 购买者信息 ===
- (void)createBuyerInformationView{
    _buyerInformationView = [[BuyerInformationView alloc] initWithFrame:CGRectMake(10,SCREEN_HEIGHT * 0.81, SCREEN_WIDTH - 20, SCREEN_HEIGHT * 0.1)];
    _buyerInformationView.backgroundColor = [UIColor lightGrayColor];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jumpToMine)];
    [_buyerInformationView addGestureRecognizer:tap];
    
   
    [self.view addSubview:_buyerInformationView];
   
}
- (void)createBuyCouponView{
    //购买企业券
    UIView *buyCouponBtnView = [[UIView alloc] initWithFrame:CGRectMake(10, SCREEN_HEIGHT * 0.92, SCREEN_WIDTH - 20, SCREEN_HEIGHT * 0.06)];
    buyCouponBtnView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:buyCouponBtnView];
    
    UIButton *buyCouponBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    buyCouponBtn.frame = CGRectMake(12, SCREEN_HEIGHT * 0.92 + 2, SCREEN_WIDTH - 24, SCREEN_HEIGHT * 0.06 - 4);
    [buyCouponBtn setTitle:@"收藏企业券" forState:UIControlStateNormal];
    [buyCouponBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    buyCouponBtn.backgroundColor = [UIColor whiteColor];
    [buyCouponBtn addTarget:self action:@selector(buyCoupon) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buyCouponBtn];
}

#pragma mark === 初始化数据源 ===
- (void)createDataArray{
    _sellRecordDataArray = [NSMutableArray array];
    _buyRecordDataArray = [NSMutableArray array];
    
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        [self getSellRecord];
        
        //获取主队列
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        dispatch_async(mainQueue, ^{
            //主线程
            [self getBuyRecord];
        });
    });

    
    [self.havingToSellTableView registerNib:[UINib nibWithNibName:@"SalesTableViewCell" bundle:nil] forCellReuseIdentifier:offerCellID];
    [self.havingToBuyTableView registerNib:[UINib nibWithNibName:@"SalesTableViewCell" bundle:nil] forCellReuseIdentifier:offerCellID];
}

#pragma mark === 网络请求 ===
- (void)getMarketPrice{
    NSDictionary *params = @{
                             };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params AndMenthodName:@"getPriceAndQty" completeBlock:^(id object) {
        
        NSLog(@"日交易量%@",object);
        NSString *str = object[@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:str];
        
        UILabel *markerPrice = (id)[self.view viewWithTag:233];
        UILabel *dayTradeQty = (id)[self.view viewWithTag:234];
        UILabel *totalTradeQty = (id)[self.view viewWithTag:235];
        
     
        if (arr == nil) {
            markerPrice.text = @"";
            dayTradeQty.text = @"";
            totalTradeQty.text = @"";
        }else{
         
            if ([arr[0][@"DayTradeQty"] isEqual:[NSNull null]]) {
                dayTradeQty.text = @"";
                
            }else{
                dayTradeQty.text = [NSString stringWithFormat:@"%@", arr[0][@"DayTradeQty"]];
                
            }
           if ([arr[0][@"MarketPrice"] isEqual:[NSNull null]]){
                markerPrice.text = @"";
                
           }else{
                markerPrice.text = [NSString stringWithFormat:@"%@", arr[0][@"MarketPrice"]];
               
           }
           
           
          if ([arr[0][@"TotalTradeQty"] isEqual:[NSNull null]]){
                totalTradeQty.text = @"";
                
            }else{
            totalTradeQty.text = [NSString stringWithFormat:@"%@", arr[0][@"TotalTradeQty"]];
            }
            
            
            
        }

    }];
}

- (void)getSellRecord{   
    NSDictionary *params = @{
                             };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params AndMenthodName:@"SellRecord" completeBlock:^(id object) {
        
        
        NSString *str = object[@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:str];
        
//        NSLog(@"%@", arr);
        
        
        for (NSDictionary *dic in arr) {
            SellRecordModel *model = [[SellRecordModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_sellRecordDataArray addObject:model];
        }
        [_havingToBuyTableView reloadData];
        
    }];

}
- (void)getBuyRecord{
    // 获取购买记录
    NSDictionary *params = @{
                             };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params AndMenthodName:@"BuyRecord" completeBlock:^(id object) {
        
        NSString *str = object[@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:str];
        
//         NSLog(@"%@", arr);
        
        
        for (NSDictionary *dic in arr) {
            BuyRecordModel *model = [[BuyRecordModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_buyRecordDataArray addObject:model];
        }
        [_havingToSellTableView reloadData];
    }];
}




#pragma mark === TableViewDelegate ===
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _havingToBuyTableView) {
        return _sellRecordDataArray.count;
    }
    return _buyRecordDataArray.count;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SalesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:offerCellID];
    
    if (tableView == _havingToBuyTableView) {
        SellRecordModel *model = _sellRecordDataArray[indexPath.row];
        cell.num.text = model.UserName;
        cell.quantity.text = [NSString stringWithFormat:@"%@", model.TradeQty];
        cell.price.text = [NSString stringWithFormat:@"%@", model.TradePrice];
    }else{
        BuyRecordModel *model = _buyRecordDataArray[indexPath.row];
        cell.num.text = model.UserName;
        cell.quantity.text = [NSString stringWithFormat:@"%@", model.TradeQty];
        cell.price.text = [NSString stringWithFormat:@"%@", model.TradePrice];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //进行购买
    if (tableView == _havingToBuyTableView) {
        HavingPurchasedViewController *purchase = [[HavingPurchasedViewController alloc] init];
        purchase.model = _sellRecordDataArray[indexPath.row];
        [self.navigationController pushViewController:purchase animated:YES];
    
    //进行出售
    }else{
        HavingSalesViewController *sales = [[HavingSalesViewController alloc] init];
        sales.model = _buyRecordDataArray[indexPath.row];
        sales.ownNumString = _buyerInformationView.ownNum;
        [self.navigationController pushViewController:sales animated:YES];
    }
}


//发布出售/发布购买
- (void)offerToSellClick{
    OfferToSellViewController *sell = [[OfferToSellViewController alloc] init];
    sell.ownNumString = _buyerInformationView.ownNum;//拥有数量
    [self.navigationController pushViewController:sell animated:YES];
}
- (void)offerToBuyClick{
    OfferToBuyViewController *buy = [[OfferToBuyViewController alloc] init];
    [self.navigationController pushViewController:buy animated:YES];
}
//购买企业券
- (void)buyCoupon{
    BuyCouponViewController *buyCoupon = [[BuyCouponViewController alloc] init];
    [self.navigationController pushViewController:buyCoupon animated:YES];
    
}
//我
- (void)jumpToMine{
    QiyequanMineViewController *qiyequan = [[QiyequanMineViewController alloc] init];
    [self.navigationController pushViewController:qiyequan animated:YES];
}


- (UITableView *)havingToSellTableView{
    if (!_havingToSellTableView) {
        
        _havingToSellTableView = [[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2 + 5,SCREEN_HEIGHT * 0.4 + 40, (SCREEN_WIDTH - 30) / 2, SCREEN_HEIGHT * 0.34 - 40)style:UITableViewStylePlain];
        _havingToSellTableView.delegate = self;
        _havingToSellTableView.dataSource = self;
        _havingToSellTableView.separatorColor = [UIColor clearColor];
        _havingToSellTableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [self.view addSubview:_havingToSellTableView];
    }
    return _havingToSellTableView;
}

- (UITableView *)havingToBuyTableView{
    if (!_havingToBuyTableView) {
        
        _havingToBuyTableView = [[UITableView alloc]initWithFrame:CGRectMake(10,SCREEN_HEIGHT * 0.4 + 40, (SCREEN_WIDTH - 30) / 2, SCREEN_HEIGHT * 0.34 - 40)style:UITableViewStylePlain];
        _havingToBuyTableView.delegate = self;
        _havingToBuyTableView.dataSource = self;
        _havingToBuyTableView.separatorColor = [UIColor clearColor];
        _havingToBuyTableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [self.view addSubview:_havingToBuyTableView];
    }
    return _havingToBuyTableView;
}


@end
